package model;

import sql.Db;
import sql.ResultSetHandler;

import java.sql.ResultSet;
import java.util.Date;

public class CommentModel {

    public String text, authorName;
    public String authorId, targetId, commentId;
    public Date date;

    public CommentModel() {
    	commentId = "";
    }

    /**
     * Construct a comment from a result set.
     * @param rs
     */
    public CommentModel (ResultSet rs) {
        try {
            text = rs.getString("text");
            authorName = rs.getString("name");
            authorId = rs.getString("authorID");
            targetId = rs.getString("targetID");
            commentId = rs.getString("id");
            date = rs.getTimestamp("timestamp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Delete this comment from the db
    public void remove() {
        Db db = Db.getDb();
        db.executeNonQuery("DELETE FROM comment WHERE id = " + commentId, new ResultSetHandler() {
            @Override
            public void handleResult(ResultSet rs) {
                commentId = ""; // clear id since we don't really exist anymore
            }
        });
    }

    /**
     * Commit this model to the db. If ID exists, then it's an update, otherwise it's an insert.
     */
    public void commit() {
        Db my_db = Db.getDb();
        if (commentId.equals("")) {
            my_db.executeNonQuery(
                "INSERT INTO comment (authorId, targetId, timestamp, text)\n" +
                "VALUES ('" + this.authorId + "','" + this.targetId + "','" +
                new java.sql.Timestamp(this.date.getTime()) + "','" + this.text + "')",

                new ResultSetHandler() {
                    @Override
                    public void handleResult(ResultSet rs) {
                        try {
                            if (rs.next()) {
                               commentId = rs.getString(1);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            );
        } else {
            my_db.executeNonQuery("UPDATE post SET "+
                "authorID = " + authorId +
                ", targetID = " + targetId +
                ", timestamp = " + date.toString() +
                ", text = " + text +
                "WHERE id = " + commentId,

                new ResultSetHandler() {
                    @Override
                    public void handleResult(ResultSet rs) {

                    }
                }
            );
        }

    }

}
